<?php
/**
 * 用户收藏
 */
namespace app\api\model;

use think\Db;
use think\Model;

class Collect extends Model{

    /**
     * 获取商品收藏列表
     */
    public function collectList($gid,$uid,$limit){
        if ($gid==0 && $uid==0){
            return false;
        }
        if ($uid > 0){
            $where['u.user_id'] = array('eq',$uid);
        }
        if ($gid > 0){
            $where['c.goods_id'] = array('eq',$gid);
        }
        //当为产品详情时只展示头像的
        if ($gid >0 && $limit==4){
            $where['u.head_pic'] = array('neq','');
        }
        $where['u.is_lock'] = 0;
        $where['g.is_on_sale'] = 1;
        $data = Db::name('goods_collect')
                    ->alias('c')
                    ->field('u.head_pic,c.collect_id,u.user_id,g.goods_id,g.original_img,g.goods_name,
                            g.market_price,g.shop_price,g.collect_sum')
                    ->join('tp_users u','c.user_id=u.user_id')
                    ->join('tp_goods g','c.goods_id=g.goods_id')
                    ->where($where)
                    ->limit($limit)
                    ->select();
        if($data){
            return $data;
        }else{
            return false;
        }

    }

    /**
     * 新增收藏
     */
    public function collectAdd($goods_id,$userid){
        if ($goods_id <= 0 || $userid <= 0){
            return false;
        }
        $map['user_id'] = $userid;
        $map['goods_id'] = $goods_id;
        $map['add_time'] = time();
        $data = Db::name('goods_collect')->insert($map);
        //添加商品中收藏
        $update = Db::execute('update tp_goods set collect_sum=collect_sum+1 where goods_id ='.$goods_id);
        if ($data){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 查询用户是否已经收藏该商品
     */
    public function collectFind($goods_id,$userid){
        if ($goods_id <=0 || $userid <= 0){
            return false;
        }
        $where['goods_id'] = $goods_id;
        $where['user_id'] = $userid;
        $data = model('goods_collect')->field('collect_id')->where($where)->find();
        if ($data){
            return $data;
        }else{
            return false;
        }
    }

    /**
     * 删除收藏
     */
    public function collectDel($goods_id,$userid){
        if ($goods_id <=0 || $userid <= 0){
            return false;
        }
        $where['goods_id'] = $goods_id;
        $where['user_id'] = $userid;
        $data = model('goods_collect')->where($where)->delete();
        if ($data){
            return $data;
        }else{
            return false;
        }
    }
}